package com.example.voicealarm;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private ListView alarmListView;
    private FloatingActionButton fabAdd;
    private AlarmAdapter adapter;
    private ArrayList<Alarm> alarms = new ArrayList<>();
    private AlarmPreferences alarmPreferences;
    
    private Handler handler = new Handler();
    private Runnable updateRunnable = new Runnable() {
        @Override
        public void run() {
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
            handler.postDelayed(this, 60000); // 每分钟更新一次
        }
    };

    private BroadcastReceiver refreshReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("com.example.voicealarm.REFRESH_ALARMS".equals(intent.getAction())) {
                Alarm currentAlarm = intent.getParcelableExtra("current_alarm");
                if (currentAlarm != null) {
                    // 更新列表中对应闹钟的贪睡状态
                    for (int i = 0; i < alarms.size(); i++) {
                        if (alarms.get(i).id == currentAlarm.id) {
                            alarms.get(i).snoozeCount = currentAlarm.snoozeCount;
                            alarms.get(i).lastSnoozeTime = currentAlarm.lastSnoozeTime;
                            break;
                        }
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        alarmPreferences = new AlarmPreferences(this);
        alarmListView = findViewById(R.id.alarm_list);
        fabAdd = findViewById(R.id.fab_add);

        // 注册广播接收器
        IntentFilter filter = new IntentFilter("com.example.voicealarm.REFRESH_ALARMS");
        registerReceiver(refreshReceiver, filter);

        // 检查并请求权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            if (!alarmManager.canScheduleExactAlarms()) {
                Intent intent = new Intent(android.provider.Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
                startActivity(intent);
            }
        }
        
        // Request SYSTEM_ALERT_WINDOW permission for showing over lock screen
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            if (!android.provider.Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    android.net.Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        }

        loadAlarms();
        setupListView();
        setupAddButton();
        handler.post(updateRunnable);
    }

    private void loadAlarms() {
        alarms.clear();
        alarms.addAll(alarmPreferences.loadAlarms());

        Collections.sort(alarms, (a1, a2) -> {
            int hour1 = a1.time.get(Calendar.HOUR_OF_DAY);
            int minute1 = a1.time.get(Calendar.MINUTE);
            int hour2 = a2.time.get(Calendar.HOUR_OF_DAY);
            int minute2 = a2.time.get(Calendar.MINUTE);
            
            if (hour1 != hour2) {
                return hour1 - hour2;
            }
            return minute1 - minute2;
        });
    }

    private void setupListView() {
        adapter = new AlarmAdapter(this, alarms);
        alarmListView.setAdapter(adapter);

        alarmListView.setOnItemClickListener((parent, view, position, id) -> {
            Alarm alarm = alarms.get(position);
            showEditAlarmDialog(alarm);
        });

    }

    private void setupAddButton() {
        fabAdd.setOnClickListener(view -> {
            Alarm newAlarm = new Alarm();
            newAlarm.time = Calendar.getInstance();
            newAlarm.ttsText = "该起床了";
            showEditAlarmDialog(newAlarm);
        });
    }

    private void showEditAlarmDialog(Alarm alarm) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_edit_alarm, null);
        builder.setView(dialogView);

        // 初始化视图
        TimePicker timePicker = dialogView.findViewById(R.id.timePicker);
        EditText etTts = dialogView.findViewById(R.id.et_tts);
        RadioGroup rgRepeat = dialogView.findViewById(R.id.rg_repeat);
        LinearLayout weekDaysContainer = dialogView.findViewById(R.id.week_days_container);
        CheckBox[] dayCheckBoxes = new CheckBox[]{
            dialogView.findViewById(R.id.cb_sun),
            dialogView.findViewById(R.id.cb_mon),
            dialogView.findViewById(R.id.cb_tue),
            dialogView.findViewById(R.id.cb_wed),
            dialogView.findViewById(R.id.cb_thu),
            dialogView.findViewById(R.id.cb_fri),
            dialogView.findViewById(R.id.cb_sat)
        };
        Button btnTest = dialogView.findViewById(R.id.btn_test);

        // 设置初始值
        timePicker.setIs24HourView(true);
        timePicker.setHour(alarm.time.get(Calendar.HOUR_OF_DAY));
        timePicker.setMinute(alarm.time.get(Calendar.MINUTE)); 
        etTts.setText(alarm.ttsText);

        // 设置重复模式
        boolean isRepeating = false;
        for (boolean day : alarm.activeDays) {
            if (day) {
                isRepeating = true;
                break;
            }
        }

        if (isRepeating) {
            rgRepeat.check(R.id.rb_repeat);
            weekDaysContainer.setVisibility(View.VISIBLE);
            for (int i = 0; i < dayCheckBoxes.length; i++) {
                dayCheckBoxes[i].setChecked(alarm.activeDays[i]);
            }
        } else {
            rgRepeat.check(R.id.rb_once);
            weekDaysContainer.setVisibility(View.GONE);
        }

        // TimePicker已自动处理时间验证

        // 重复模式切换
        rgRepeat.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_repeat) {
                weekDaysContainer.setVisibility(View.VISIBLE);
            } else {
                weekDaysContainer.setVisibility(View.GONE);
            }
        });

        AlertDialog dialog = builder.create();

        // 测试按钮
        btnTest.setOnClickListener(v -> {            // 使用当前时间立即测试闹钟
            Calendar testTime = Calendar.getInstance();
            
            Alarm testAlarm = new Alarm();
            testAlarm.id = System.currentTimeMillis();
            testAlarm.time = testTime;
            testAlarm.ttsText = etTts.getText().toString();
            Arrays.fill(testAlarm.activeDays, false); // Test alarm should not repeat

            // Start RingActivity directly
            Intent intent = new Intent(MainActivity.this, RingActivity.class);
            intent.putExtra("alarm", testAlarm);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            Toast.makeText(MainActivity.this, "正在测试闹钟", Toast.LENGTH_SHORT).show();
        });

        // 保存按钮
        dialogView.findViewById(R.id.btn_save).setOnClickListener(v -> {
            // 更新闹钟数据
            alarm.time.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
            alarm.time.set(Calendar.MINUTE, timePicker.getMinute());
            alarm.time.set(Calendar.SECOND, 0);
            alarm.expired = false;  // 重置过期状态

            alarm.ttsText = etTts.getText().toString();

            // 设置星期
            boolean isRepeat = rgRepeat.getCheckedRadioButtonId() == R.id.rb_repeat;
            if (isRepeat) {
                for (int i = 0; i < dayCheckBoxes.length; i++) {
                    alarm.activeDays[i] = dayCheckBoxes[i].isChecked();
                }
            } else {
                Arrays.fill(alarm.activeDays, false);
            }

            // 如果是新闹钟，添加到列表
            if (alarm.id == 0) {
                alarm.id = System.currentTimeMillis();
                alarms.add(alarm);
            }

            // 更新列表
            Collections.sort(alarms, (a1, a2) -> {
                int hour1 = a1.time.get(Calendar.HOUR_OF_DAY);
                int minute1 = a1.time.get(Calendar.MINUTE);
                int hour2 = a2.time.get(Calendar.HOUR_OF_DAY);
                int minute2 = a2.time.get(Calendar.MINUTE);
                
                if (hour1 != hour2) {
                    return hour1 - hour2;
                }
                return minute1 - minute2;
            });
            adapter.notifyDataSetChanged();

            // 保存到SharedPreferences
            alarmPreferences.saveAlarms(alarms);

            // 调度闹钟
            saveOrScheduleAlarm(alarm);
            Toast.makeText(MainActivity.this, "闹钟已保存", Toast.LENGTH_SHORT).show();

            dialog.dismiss();
        });

        // 取消按钮
        dialogView.findViewById(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());

        dialog.show();
    }

    private void saveOrScheduleAlarm(Alarm alarm) {
        Intent intent = new Intent(this, AlarmService.class);
        intent.setAction("SCHEDULE_ALARM");
        intent.putExtra("alarm", alarm);
        startService(intent);
    }

    private void deleteAlarm(Alarm alarm) {
        // Cancel scheduled alarm
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this,
                (int) alarm.id,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);

        // Remove from list and update adapter
        alarms.remove(alarm);
        Collections.sort(alarms, (a1, a2) -> {
            int hour1 = a1.time.get(Calendar.HOUR_OF_DAY);
            int minute1 = a1.time.get(Calendar.MINUTE);
            int hour2 = a2.time.get(Calendar.HOUR_OF_DAY);
            int minute2 = a2.time.get(Calendar.MINUTE);
            
            if (hour1 != hour2) {
                return hour1 - hour2;
            }
            return minute1 - minute2;
        });
        adapter.notifyDataSetChanged();

        // Save to SharedPreferences
        alarmPreferences.saveAlarms(alarms);

        // Show confirmation
        Toast.makeText(this, "闹钟已删除", Toast.LENGTH_SHORT).show();
    }

    private class AlarmAdapter extends ArrayAdapter<Alarm> {
        public AlarmAdapter(MainActivity context, ArrayList<Alarm> alarms) {
            super(context, 0, alarms);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Alarm alarm = getItem(position);
            
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.alarm_item, parent, false);
            }
            
            TextView tvTime = convertView.findViewById(R.id.tv_time);
            TextView tvDays = convertView.findViewById(R.id.tv_days);
            TextView tvTts = convertView.findViewById(R.id.tv_tts);
            TextView tvRepeat = convertView.findViewById(R.id.tv_repeat);
            ImageButton btnDelete = convertView.findViewById(R.id.btn_delete);
            TextView tvNextRing = convertView.findViewById(R.id.tv_next_ring);
            
            if (alarm != null) {
                tvTime.setText(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(alarm.time.getTime()));
                
                String[] days = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < alarm.activeDays.length; i++) {
                    if (alarm.activeDays[i]) {
                        if (sb.length() > 0) sb.append(",");
                        sb.append(days[i]);
                    }
                }
                tvDays.setText(sb.toString());
                tvTts.setText(alarm.ttsText);
                // 优先显示贪睡状态，如果没有则显示下次响铃时间
                String snoozeStatus = alarm.getSnoozeStatus();
                tvNextRing.setText(snoozeStatus != null ? snoozeStatus : alarm.getTimeUntilNextAlarm());
                tvRepeat.setText(alarm.isRepeating() ? "每周重复" : "只响一次");
                btnDelete.setOnClickListener(v -> {
                    deleteAlarm(alarm);
                });
                
                // 根据闹钟状态设置颜色
                int textColor = alarm.isExpired() ? Color.GRAY : Color.BLACK;
                tvTime.setTextColor(textColor);
                tvDays.setTextColor(textColor);
                tvTts.setTextColor(textColor);
                tvRepeat.setTextColor(textColor);
                tvNextRing.setTextColor(snoozeStatus != null ? Color.RED : textColor);
            }
            
            return convertView;
        }
    }
}